package com.itheima.controller;

import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        PageBean<User> userPageBean = userService.selectByPage(currentPage, pageSize);
        if(userPageBean!=null){
            Result result = new Result(1,userPageBean);
            return result;
        }else{
            Result result = new Result(0,"查询失败");
            return result;
        }
    }
    /**
     * 保存用户
     * @param user 用户数据
     * @return
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        int i = userService.add(user);
        if(i>0){
            Result result = new Result(20011);
            return result;
        }else{
            Result result = new Result(20010);
            return result;
        }
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userService.deleteById(id);
        if (i>0){
            Result result = new Result(20021);
            return result;
        }else {
            Result result = new Result(20020);
            return result;
        }
    }

    /**
     * 更新用户
     * @param user 用户数据
     * @return
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        int i = userService.update(user);
        if (i>0){
            Result result = new Result(20031);
            return result;
        }else {
            Result result = new Result(20030);
            return result;
        }
    }

}
